import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:hbtrans_flutter/beans/detailbyid_bean.dart';
import 'package:hbtrans_flutter/beans/list_bean.dart';
import 'package:hbtrans_flutter/utils/mydio.dart';
import 'package:hbtrans_flutter/view/loading.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../const.dart';
import '../routes.dart';

class TesterSearch extends StatefulWidget {
  @override
  _TesterSearchState createState() => _TesterSearchState();
}

class PanelTitle extends StatelessWidget {
  final String title;

  const PanelTitle({Key key, this.title}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      padding: EdgeInsets.fromLTRB(20, 8, 0, 8),
      child: Row(
        children: <Widget>[
          Image.asset(
            'images/icon_leixing.png',
            height: 24,
            width: 24,
            fit: BoxFit.fill,
          ),
          SizedBox(
            width: 5,
          ),
          Text(
            title,
            style: TextStyle(color: Color(0xff333333), fontSize: 16),
          )
        ],
      ),
    );
  }
}

class _TesterSearchState extends State<TesterSearch> {
  String status = '';
  String organizId = '';
  String sonOrganizId = '';

  String loginOrganiz = '',
      loginSonOrganiz = '',
      loginType = '',
      loginAdname = '';

  bool isGeted = false;
  var titles = ['管辖机构', '审核状态'];

  var loadingDialog;
  List selected = ['', '', ''];
  List<ListBean> _sub1 = List();
  var _sub2 = <String>['待审核', '审核通过'];
  var _sub2Result = <String>['2', '1'];

  List<DataListBean4> _sub4 = List();
  List<bool> _checks = List();

  var currentPanelIndex = -1; // -1默认全部闭合
  List<int> mList;
  ExpansionPanelList _expansionPanelList;

  _TesterSearchState() {
    mList = List();
    for (int i = 0; i < titles.length; i++) {
      mList.add(i);
    }
  }

  _setIcon(bool b) {
    if (b) {
      return Icon(Icons.check_box, color: Color(0xff23AFDC), size: 20);
    } else {
      return Icon(Icons.check_box_outline_blank,
          color: Color(0xff999999), size: 20);
    }
  }

  _setListChoice(List<DataListBean4> beans, List<bool> checks) {
    List<Widget> list = List();
    for (int i = 0; i < beans.length; i++) {
      list.add(Padding(
        padding: const EdgeInsets.fromLTRB(20, 0, 20, 0),
        child: GestureDetector(
          onTap: () {
//            //重置列表选择项
//            int _length = _checks.length;
//            _checks.clear();
//            for (int i = 0; i < _length; i++) {
//              _checks.add(false);
//            }
//            setState(() {
//              checks[i] = !checks[i];
//              sonOrganizId = beans[i].id;
//              print('organizId:$organizId,sonOrganizId:$sonOrganizId');
//            });
            _setTypeListChoice(i, beans, checks);
          },
          child: Card(
            color: Colors.white,
            elevation: 0,
            child: SizedBox(
              height: 40,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Text(
                    beans[i].name,
                    style: TextStyle(color: Color(0xff333333), fontSize: 14),
                  ),
                  _setIcon(checks[i])
                ],
              ),
            ),
          ),
        ),
      ));
    }
    return Column(children: list);
  }

  _setTypeListChoice(int i, List<DataListBean4> beans, List<bool> checks) {
    if (loginType == '3') {
    } else {
      //重置列表选择项
      int _length = _checks.length;
      _checks.clear();
      for (int i = 0; i < _length; i++) {
        _checks.add(false);
      }
      setState(() {
        checks[i] = !checks[i];
        sonOrganizId = beans[i].id;
        print('organizId:$organizId,sonOrganizId:$sonOrganizId');
      });
    }
  }

  _setTypeChoiceChip1(int index, bool value, ListBean bean) {
    if (loginType == '2') {
    } else if (loginType == '3') {
    } else {
      setState(() {
        selected[index] = value ? bean.name : '';
        if (selected[0] == '') {
          organizId = '';
          _sub4.clear();
        } else {
          organizId = bean.id;
          _detailById(organizId);
        }
        print('_result:${selected[0]}_organizId:$organizId');
      });
    }
  }

  _setTypeChoiceChip1Selected(int index, ListBean bean) {
    if (loginType == '2' || loginType == '3') {
      if (loginOrganiz == bean.id) {
        if (!isGeted) {
          _detailById(bean.id);
        }
      }
      return loginOrganiz == bean.id;
    } else {
      return selected[index] == bean.name;
    }
  }

  _setChoiceChip1(List<ListBean> beans, int index) {
    List<Widget> list = List();
    for (ListBean bean in beans) {
      list.add(ChoiceChip(
        shadowColor: Colors.transparent,
        selectedColor: Color(0x5A23AFDC),
        backgroundColor: Colors.grey[100],
        label: Text('${bean.name.split('市')[0]}'),
        labelStyle: TextStyle(color: Color(0xff666666), fontSize: 14),
        materialTapTargetSize: MaterialTapTargetSize.padded,
        onSelected: (bool value) {
//          setState(() {
//            selected[index] = value ? bean.name : '';
//            if (selected[0] == '') {
//              organizId = '';
//              _sub4.clear();
//            } else {
//              organizId = bean.id;
//              _detailById(organizId);
//            }
//            print('_result:${selected[0]}_organizId:$organizId');
//          });
          _setTypeChoiceChip1(index, value, bean);
        },
//        selected: selected[index] == bean.name,
        selected: _setTypeChoiceChip1Selected(index, bean),
      ));
    }

    return Padding(
      padding: const EdgeInsets.fromLTRB(20, 0, 20, 10),
      child: SizedBox(
        width: MediaQuery.of(context).size.width,
        child: Wrap(
          spacing: 20,
          runSpacing: 10,
          children: list,
        ),
      ),
    );
  }

  _setChoiceChip2(List<String> sub, int index) {
    List<Widget> list = List();
    for (int i = 0; i < sub.length; i++) {
      list.add(ChoiceChip(
        shadowColor: Colors.transparent,
        selectedColor: Color(0x5A23AFDC),
        backgroundColor: Colors.grey[100],
        label: Text(sub[i]),
        labelStyle: TextStyle(color: Color(0xff666666), fontSize: 14),
        materialTapTargetSize: MaterialTapTargetSize.padded,
        onSelected: (bool value) {
          setState(() {
            selected[index] = value ? sub[i] : '';
            switch (index) {
              case 1:
                selected[index] == '' ? status = '' : status = _sub2Result[i];
                break;
            }

            print('status:$status,status:$status');
          });
        },
        selected: selected[index] == sub[i],
      ));
    }

    return Padding(
      padding: const EdgeInsets.fromLTRB(20, 0, 20, 10),
      child: SizedBox(
        width: MediaQuery.of(context).size.width,
        child: Wrap(
          spacing: 20,
          runSpacing: 10,
          children: list,
        ),
      ),
    );
  }

  _setChoiceChips() {
    return [
      Column(
        children: <Widget>[
          _setChoiceChip1(_sub1, 0),
          Container(
            height: 1,
            color: Colors.grey[300],
          ),
          _setListChoice(_sub4, _checks)
        ],
      ),
      _setChoiceChip2(_sub2, 1),
    ];
  }

  _getType() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      loginType = prefs.getString('loginType');
      loginAdname = prefs.getString('loginAdname');
      if (loginType == '2') {
        loginOrganiz = prefs.getString('loginOrganiz');
      } else if (loginType == '3') {
        loginOrganiz = prefs.getString('loginOrganiz');
        loginSonOrganiz = prefs.getString('loginSonOrganiz');
      }
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _list();
    _getType();
  }

  @override
  Widget build(BuildContext context) {
    _expansionPanelList = ExpansionPanelList(
      animationDuration: Duration(milliseconds: 500),
      expansionCallback: (panelIndex, isExpanded) {
        setState(() {
          currentPanelIndex =
              (currentPanelIndex != panelIndex) ? panelIndex : -1;
        });
      },
      children: mList.map((i) {
        return ExpansionPanel(
          canTapOnHeader: true,
          headerBuilder: (context, isExpanded) {
            return PanelTitle(
              title: titles[i],
            );
          },
          body: _setChoiceChips()[i],
          isExpanded: currentPanelIndex == i,
        );
      }).toList(),
    );

    return Scaffold(
      appBar: AppBar(
        title: Text('搜索'),
        backgroundColor: Color(0xff23AFDC),
        elevation: 0,
        centerTitle: true,
        actions: <Widget>[
          IconButton(
              icon: Icon(
                Icons.search,
                color: Colors.white,
              ),
              onPressed: () {
                String route =
                    '${Routes.testerPage}?status=$status&organizId=$organizId&sonOrganizId=$sonOrganizId';
                Routes.router.navigateTo(context, route,
                    replace: true, transition: TransitionType.fadeIn);
              }),
        ],
      ),
      body: Column(
        children: <Widget>[
          Expanded(
            child: ListView(
              children: <Widget>[
                Column(
                  children: <Widget>[
                    _expansionPanelList,
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  _showDialog() {
    loadingDialog = LoadingDialog(
      text: '加载中...',
    );
    showDialog<Null>(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return loadingDialog;
        });
  }

  _list() async {
    MyDio.getInstance().get(
      '/api/organiz/list',
      (data) {
        if (loadingDialog != null) {
          loadingDialog = null;
          Navigator.pop(context);
        }
        for (var s in data) {
          _sub1.add(ListBean.fromJson(s));
        }
        setState(() {});
      },
    );
  }

  Future<Null> _detailById(String id) async {
    //    _showDialog();
    isGeted = true;
    Map data = Map<String, dynamic>();
    data["id"] = id;
    try {
      Dio dio = Dio(Const.get);
      print(dio.options.method);
      Response response =
          await dio.request('/api/organiz/detailById', queryParameters: data);

      if (loadingDialog != null) {
        loadingDialog = null;
        Navigator.pop(context);
      }

      Map<String, dynamic> decoded = json.decode(response.toString());
      print('response:$response');
      DetailbyidBean detailbyidBean = DetailbyidBean.fromJson(decoded);
      //重置列表选择项
      _checks.clear();
      for (int i = 0; i < detailbyidBean.data.length; i++) {
//        _checks.add(false);
        if (loginType == '3') {
          sonOrganizId = loginSonOrganiz;
          _checks.add(detailbyidBean.data[i].id == loginSonOrganiz);
        } else {
          _checks.add(false);
        }
      }
      setState(() {
        _sub4 = detailbyidBean.data;
      });
    } catch (e) {
      print(e);
    }
  }
}
